<template>
    <!-- AI聊天历史弹窗 -->
    <uni-popup ref="popup" type="left" :animation="true" :mask-click="true" @change="onPopupChange" :safe-area="false">

        <view class="ai-history-content">
            <!-- 聊天历史列表 -->
            <scroll-view class="scrollable-content history-list" scroll-y>
                <view class="history-section" v-for="section in chatHistory" :key="section.date">
                    <view class="date-header">{{ section.date }}</view>
                    <view class="chat-items">
                        <view class="chat-item" v-for="chat in section.chats" :key="chat.id" @click="selectChat(chat)"
                            :class="{ 'active': currentChatId === chat.id }">
                            <text class="chat-title">{{ chat.title }}</text>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
    </uni-popup>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const popup = ref(null)
const currentChatId = ref(null)

// 定义props来接收外部数据
const props = defineProps({
    currentMessages: {
        type: Array,
        default: () => []
    },
    currentChatTitle: {
        type: String,
        default: ''
    }
})

// 聊天历史数据 - 从本地存储获取
const chatHistory = ref([])

// 从本地存储加载聊天历史
const loadChatHistory = () => {
    try {
        const history = uni.getStorageSync('ai_chat_history')
        if (history) {
            chatHistory.value = JSON.parse(history)
        } else {
            // 如果没有历史数据，初始化一些示例数据
            chatHistory.value = [
                {
                    date: '2025年4月10日',
                    chats: [
                        { id: 1, title: '为什么世界有形成?', messages: [] },
                        { id: 2, title: '什么是人工智能?', messages: [] },
                        { id: 3, title: '如何学习编程?', messages: [] },
                        { id: 4, title: '为什么会有这个世界?', messages: [] },
                    ]
                }
            ]
        }
    } catch (error) {
        console.error('加载聊天历史失败:', error)
        chatHistory.value = []
    }
}

// 保存聊天历史到本地存储
const saveChatHistory = () => {
    try {
        uni.setStorageSync('ai_chat_history', JSON.stringify(chatHistory.value))
    } catch (error) {
        console.error('保存聊天历史失败:', error)
    }
}

// 打开AI历史
const openAiHistory = () => {
    popup.value.open()
}

// 关闭AI历史
const closeHistory = () => {
    popup.value.close()
}

// 弹窗状态变化
const onPopupChange = (e) => {
    console.log('弹窗状态变化:', e)
}

// 选择聊天
const selectChat = (chat) => {
    currentChatId.value = chat.id
    // 这里可以添加加载聊天记录的逻辑
    uni.showToast({
        title: `选择了: ${chat.title}`,
        icon: 'none'
    })
    closeHistory()
}

// 保存当前对话到历史记录
const saveCurrentChat = (title, messages) => {
    if (!title || !messages || messages.length === 0) return
    
    const today = new Date()
    const dateStr = `${today.getFullYear()}年${today.getMonth() + 1}月${today.getDate()}日`
    const newChatId = Date.now() // 使用时间戳作为ID
    
    const newChat = {
        id: newChatId,
        title: title,
        messages: messages,
        timestamp: today
    }
    
    // 查找今天的日期组
    let todaySection = chatHistory.value.find(section => section.date === dateStr)
    
    if (!todaySection) {
        // 如果没有今天的日期组，创建一个
        todaySection = {
            date: dateStr,
            chats: []
        }
        chatHistory.value.unshift(todaySection) // 添加到最前面
    }
    
    // 添加到今天的聊天列表
    todaySection.chats.unshift(newChat) // 最新的聊天在最前面
    
    // 限制每天最多保存20个对话
    if (todaySection.chats.length > 20) {
        todaySection.chats = todaySection.chats.slice(0, 20)
    }
    
    // 保存到本地存储
    saveChatHistory()
}

// 新建对话
const newChat = () => {
    uni.showToast({
        title: '新建对话',
        icon: 'success'
    })
    closeHistory()
}

// 清空历史
const clearHistory = () => {
    uni.showModal({
        title: '确认清空',
        content: '确定要清空所有聊天历史吗？',
        success: (res) => {
            if (res.confirm) {
                chatHistory.value = []
                uni.showToast({
                    title: '已清空历史',
                    icon: 'success'
                })
            }
        }
    })
}

// 生命周期
onMounted(() => {
    loadChatHistory()
})

defineExpose({
    openAiHistory,
    saveCurrentChat,
    loadChatHistory
})
</script>

<style lang="scss" scoped>
.ai-history-content {
    width: 600rpx;
    height: 100vh;
    background: #fff;
    display: flex;
    flex-direction: column;
    position: relative;
    padding-top: 70rpx;
    box-sizing: border-box;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx 32rpx 20rpx;
    background: #f0f0f0;
    border-bottom: 1rpx solid #e0e0e0;
    
    .title {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
    }
    
    .close-btn {
        padding: 10rpx;
        cursor: pointer;
    }
}

.history-list {
    flex: 1;
    padding: 32rpx 32rpx;
    box-sizing: border-box;
}

.history-section {
    margin-bottom: 40rpx;
    
    .date-header {
        font-size: 26rpx;
        color: #999;
        margin-bottom: 12rpx;
        font-weight: 500;
    }
    
    .chat-items {
        display: flex;
        flex-direction: column;
        gap: 12rpx;
    }
    
    .chat-item {
        cursor: pointer;
        transition: all 0.2s ease;
        // border-left: 4rpx solid transparent;
        
        &:hover {
            background: #f8f8f8;
        }
        
        &.active {
            background: #e8f4ff;
        }
        
        .chat-title {
            font-size: 26rpx;
            color: #333;
            line-height: 1.4;
            word-break: break-word;
        }
    }
}

.bottom-actions {
    display: flex;
    gap: 20rpx;
    padding: 32rpx;
    background: #f0f0f0;
    border-top: 1rpx solid #e0e0e0;
    
    .action-btn {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12rpx;
        padding: 24rpx;
        background: #fff;
        border-radius: 16rpx;
        cursor: pointer;
        transition: all 0.2s ease;
        
        &:hover {
            background: #f8f8f8;
        }
        
        .action-text {
            font-size: 28rpx;
            color: #333;
        }
    }
}

// 响应式设计
@media (max-width: 750rpx) {
    .ai-history-content {
        width: 100vw;
    }
}
</style>
